﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace GetHistoryData
{
    public partial class GetHistoryData : Form
    {
        SohuHistoryPriceProvider sp = new SohuHistoryPriceProvider();

        public GetHistoryData()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + AppSettings.GetValue<string>("DailySavePath");

            if (MessageBox.Show("您确定要补充所有股票的历史行情吗？建议先备份现有数据", "提醒", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == System.Windows.Forms.DialogResult.No)
                return;

            LogText("共{0}只股票的历史行情开始补充...", StockListXXX.Instance.AllStock.Count);

            //StockListConfig.Instance.AllStock
            foreach (var item in StockListXXX.Instance.AllStock)
            {
                DoWork(path, item);
            }
        }

        private void DoWork(string path, StockListItem item)
        {
            int count = 0;
            try
            {
                List<LSStockPrice> list = new List<LSStockPrice>();

                if (!File.Exists(Application.StartupPath + AppSettings.GetValue<string>("DailyOldPath") + item.StockCode + ".txt"))
                    LogText("没有找到【{0}】的历史行情价格", this.cbStockCode.Text);
                else
                    File.ReadAllLines(Application.StartupPath + AppSettings.GetValue<string>("DailyOldPath") + item.StockCode + ".txt").ToList().ForEach(l => list.Add(new LSStockPrice() { Date = Convert.ToDateTime(l.Split(',')[0]), ClosePrice = Convert.ToDouble(l.Split(',')[1]) }));

                Dictionary<DateTime, LSStockPrice> dic = list.ToDictionary(l => l.Date);

                sp.GetHistoryPrice(item.StockCode, 100)
                    .ForEach(p =>
                    {
                        if (!dic.ContainsKey(p.Date))
                        {
                            list.Add(p); count++;
                        }
                    });

                StringBuilder sb = new StringBuilder();
                list.OrderBy(l => l.Date).ToList().ForEach(p => sb.AppendLine(string.Format("{0},{1}", p.Date.ToString("yyyy-MM-dd"), p.ClosePrice.ToString(".00"))));

                File.WriteAllText(path + item.StockCode + ".txt", sb.ToString());

                LogText("{0} 历史行情已补充，增补了{1}天的历史行情", item.StockCode, count);
            }
            catch (Exception ex)
            {
                LogText("{0}（{2}） 出错：{1}\n", item.StockCode, ex.Message, item.StockName);
            }
        }

        private void GetHistoryData_Load(object sender, EventArgs e)
        {
            this.cbStockCode.DataSource = StockListConfig.Instance.AllStock;
            this.cbStockCode.DisplayMember = "StockName";
            this.cbStockCode.ValueMember = "StockCode";
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            List<LSStockPrice> list = new List<LSStockPrice>();
            if (!File.Exists(Application.StartupPath + AppSettings.GetValue<string>("DailyOldPath") + this.cbStockCode.SelectedValue + ".txt"))
            {
                LogText("没有找到【{0}】的历史行情价格，请检查是否有此文件：{1}.txt", this.cbStockCode.Text, this.cbStockCode.SelectedValue);
                this.dgvPrice.DataSource = list;
                return;
            }

            var txt = File.ReadAllLines(Application.StartupPath + AppSettings.GetValue<string>("DailyOldPath") + this.cbStockCode.SelectedValue + ".txt");

            if (txt.Count() == 0)
            {
                LogText("没有找到【{0}】的历史行情价格", this.cbStockCode.Text);
                return;
            }

            txt.ToList().ForEach(l => list.Add(new LSStockPrice() { StockCode = this.cbStockCode.Text, Date = Convert.ToDateTime(l.Split(',')[0]), ClosePrice = Convert.ToDouble(l.Split(',')[1]) }));



            this.dgvPrice.DataSource = list.OrderByDescending(l => l.Date).ToList();

            LogText("【{0}】目前已保存{1}条历史行情\n最近一次为：{2}\n距今已有 {3} 天", this.cbStockCode.Text, list.Count, list.LastOrDefault().Date.ToShortDateString(), (DateTime.Today - list.LastOrDefault().Date).TotalDays);
        }

        private void LogText(string msg, params object[] args)
        {
            this.richTextBox1.AppendText(string.Format(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "：" + msg, args));
            this.richTextBox1.AppendText("\n\n");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确定要补充【" + this.cbStockCode.Text + "】的历史行情吗？建议先备份现有数据", "提醒", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == System.Windows.Forms.DialogResult.No)
                return;

            var item = StockListConfig.Instance.AllStock.Find(s => s.StockCode == this.cbStockCode.SelectedValue.ToString());
            DoWork(Application.StartupPath + AppSettings.GetValue<string>("DailySavePath"), item);
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            frmPriceEdit edit = new frmPriceEdit(this.cbStockCode.Text, this.cbStockCode.SelectedValue.ToString());

            if (edit.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                btnQuery_Click(sender, e);
            }
        }

        private void 编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.dgvPrice.SelectedRows.Count == 0)
                return;

            var date = Convert.ToDateTime(this.dgvPrice.SelectedRows[0].Cells[1].Value);
            var price = Convert.ToDouble(this.dgvPrice.SelectedRows[0].Cells[2].Value);

            frmPriceEdit edit = new frmPriceEdit(this.cbStockCode.Text, this.cbStockCode.SelectedValue.ToString(), date, price);

            if (edit.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                btnQuery_Click(sender, e);
            }
        }

        private void dgvPrice_DoubleClick(object sender, EventArgs e)
        {
            编辑ToolStripMenuItem_Click(sender, e);
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.dgvPrice.SelectedRows.Count == 0)
                return;
            
            var date = Convert.ToDateTime(this.dgvPrice.SelectedRows[0].Cells[1].Value);
            var price = Convert.ToDouble(this.dgvPrice.SelectedRows[0].Cells[2].Value);

            if (MessageBox.Show(string.Format("您确定要删除【{0}】{1}的行情数据吗？删除后将不可恢复，请谨慎操作", this.cbStockCode.Text, date), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {

            }
        }
    }
}
